const express = require('express')
const router = express.Router()
const connection = require('../mysql');
// const e = require('express');


router.post('/submitOrder', (req, res) => {
    //创建以时间戳为名称的订单id
    function formatTimestampToDateTime(timestamp) {
        const date = new Date(timestamp); 
        const year = date.getFullYear(); 
        const month = String(date.getMonth() + 1).padStart(2, '0'); 
        const day = String(date.getDate()).padStart(2, '0'); 
        const hours = String(date.getHours()).padStart(2, '0'); 
        const minutes = String(date.getMinutes()).padStart(2, '0'); 
        const seconds = String(date.getSeconds()).padStart(2, '0'); 
    
        return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`; 
    }
    const currentTimestamp = Date.now(); 
    const formattedDateTime = formatTimestampToDateTime(currentTimestamp);

    const {g_id, g_name, uname, t_price, t_num, g_pic, name, tel, addres} = req.body.params;
    
    const sql = 'insert into goods_order ( o_id, g_id, g_name, t_price, t_num, g_pic, username, name, tel, addres) values (?,?,?,?,?,?,?,?,?,?)';

    connection.query(sql, [formattedDateTime, g_id, g_name, t_price,t_num, g_pic, uname, name, tel, addres],(err, result) =>{
        if (err) res.send(err)
        console.log(result);
        // res.send('ok')
        if (result.affectedRows === 1) {
            res.send({
                status: 200,
                msg: '提交订单成功'
            })
        }else{
            res.send({
                status: 400,
                msg: '提交订单失败'
            })
        }
    })
})


//! 用户订单列表
router.post('/orderList', (req, res) =>{
    console.log(req.body.params);
    const {uname} = req.body.params;
    const sql ='select * from goods_order where username =?';

    connection.query(sql, [uname], (err, result) => {
        if (err) res.send(err)
        
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result
            })
        }else{
            res.send({
                status: 400,
                msg: '暂无订单'
            })
        }
    })


})


module.exports = router;